package org.apache.ibatis.demo.handler;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Optional;

/**
 * JsonHandler
 *
 * @author zhaohui
 */
public class JsonHandler implements TypeHandler<String> {

    private Gson gson = new Gson();

    @Override
    public void setParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        ps.setObject(i, new Gson().toJson(parameter));
    }

    @Override
    public String getResult(ResultSet rs, String columnName) throws SQLException {
        String value = (String) rs.getObject(columnName);
        JsonObject json = Optional.ofNullable(gson.fromJson(value, JsonObject.class)).orElse(new JsonObject());
        return 0 == json.size() ? null : value;
    }

    @Override
    public String getResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = (String) rs.getObject(columnIndex);
        JsonObject json = Optional.ofNullable(gson.fromJson(value, JsonObject.class)).orElse(new JsonObject());
        return 0 == json.size() ? null : value;
    }

    @Override
    public String getResult(CallableStatement cs, int columnIndex) throws SQLException {
        return null;
    }
}
